package com.syn.syn1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Auther: zch
 * @Date: 2019/1/7 14:53
 * @Description: 限时等待锁
 */
public class TimeLock implements Runnable {
    public static void main(String[] args) throws InterruptedException {

        TimeLock timeLock = new TimeLock();
        Thread t1 = new Thread(timeLock);
        Thread t2 = new Thread(timeLock);
        t1.start();

        t2.start();

    }

    public static ReentrantLock lock=new ReentrantLock();

    @Override
    public void run()  {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)) {

                Thread.sleep(6000);
            } else {
                System.out.println("get lock failed");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }
}
